package com.softeem.controller;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.softeem.pojo.Admin;
import com.softeem.pojo.model.LoginModel;
import com.softeem.service.AdminService;
import com.softeem.shiro.JwtUtils;
import com.softeem.util.ResultBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AdminController {

    @Autowired
    AdminService adminService;

    @Autowired
    JwtUtils jwtUtils;



    @PostMapping("/login")
    public ResultBean  login(@RequestBody LoginModel loginModel,
                            HttpServletResponse response){
        //1.调用service层中的方法
        Admin admin = adminService.login(loginModel);
        if(admin ==null){
            return ResultBean.fail("用户名或者密码错误!");
        }

        //2. 生成jwt
        String jwt = jwtUtils.generateToken(admin.getId());

        System.out.println("jwt = " + jwt);


        //3.将生成的jwt传递给浏览器客户端
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-Control-Expose-Headers","Authorization");

        MapBuilder<Object, Object> mapBuilder = MapUtil.builder().put(
                "id", admin.getId()).put("name", admin.getName())
                .put("img", admin.getImg()).put("email", admin.getEmail());
        return ResultBean.success("",mapBuilder.map());
    }



    //退出的接口
    @GetMapping("/logout")
    public ResultBean logout(){
        SecurityUtils.getSubject().logout(); //交给shiro完成安全退出
        return ResultBean.success("安全退出");
    }


    @RequiresAuthentication
    @GetMapping("/adminInfo/{id}")
    public ResultBean<Admin>  getAdminInfo(@PathVariable("id")int id){
        Admin admin = adminService.getAdmin(id);
        if(admin == null){
            return ResultBean.fail(400,"用户不存在!");
        }
        return ResultBean.success("用户信息",admin);
    }


    //只能是拥有vipUser角色用户可以访问这个方法
    @GetMapping("/m1")
    @RequiresRoles("vipUser")  // 会去调用AccountRealm中的授权的方法doGetAuthorizationInfo
    public ResultBean m1(){
        System.out.println("m1 方法执行了" );
        return ResultBean.success("m1 execute");
    }



    @RequiresPermissions("admin:add")
    @GetMapping("/admin/add")
    public ResultBean addAdmin(){
        return ResultBean.success("addAdmin方法能够访问");
    }

}
